package sw6.admin.gui;

import java.io.IOException;
import java.io.InputStream;

import org.xml.sax.SAXException;

import sw6.admin.R;
import sw6.admin.gui.logic.Menu;
import sw6.admin.gui.logic.Serializer;
import sw6.admin.gui.logic.SettingParser;
import sw6.admin.internal.Definitions;
import sw6.admin.parser.SettingsParser;
import sw6.lib.Settings;
import sw6.lib.internal.PrivateDefinitions;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.os.Bundle;

public class FirstRunActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Welcome to GIRAF. This is the fist time you have turned on your device. It is recommended that you set up the user profile for the child that will be using the system.")
		.setCancelable(false)
		.setPositiveButton("Setup User Profile", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				Settings.setBoolean(FirstRunActivity.this, "isFirstRun", false);
				startMenuActivity();
				finish();
			}
		})
		.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				Settings.setBoolean(FirstRunActivity.this, "isFirstRun", false);
				dialog.cancel();
				finish();
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}

	private void startMenuActivity() {

		AssetManager am = null;

		// Retrieves the asset manager for the app in question
		try {
			am = SettingsParser.getAssetsByAppName(FirstRunActivity.this, Definitions.SW6_ADMIN_PACKAGE_NAME);
		} catch (NameNotFoundException e1) {
		}

		try {
			InputStream is = am.open(PrivateDefinitions.SETTINGS_FILE_NAME);

			// Parses the settings file for the app as a tree structure with root "menu"
			Menu menu = SettingParser.loadXML(is, Definitions.SW6_ADMIN_PACKAGE_NAME, this.getPackageManager());

			menu = menu.getMenus().get(0);

			// Serialized menu so that it can be sent to MenuActivity
			byte[] bytes = Serializer.serializeObject(menu);
			Intent intent = new Intent();

			intent.setClassName(this, "sw6.admin.gui.MenuActivity");
			intent.putExtra("menuBytes", bytes);

			startActivity(intent);

		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
	}
}
